package basicComp;

import javax.swing.Icon;
import javax.swing.JLabel;

/**
 * 
 * @author NHQ
 *
 */
public class BasicAnimPanel extends JLabel
{
	private int index;
	private Icon [] anim;
	private int repeatIniTime = 3;
	private int frameIniTime = 3;
	
	private int repeatTime;
	private int frameTime;
	
	private boolean start;
	private boolean over = true;
	
	private int lastShow;
	public BasicAnimPanel(Icon...icons)
	{
		super(icons[0]);
		this.anim = icons;
	}
	/**
	 * 设置每次播放重复次数和单帧持续时间
	 * @param repeatTime 每次播放重复次数，默认为3
	 * @param frameTime 单帧持续时间,默认为20
	 */
	public void init(int repeatTime, int frameTime)
	{
		this.repeatIniTime = repeatTime;
		this.frameIniTime = frameTime;
	}
	public void start()
	{
		if(isStart())
		{
			return;
		}
		repeatTime = repeatIniTime;
		frameTime = frameIniTime;
		new Thread(new AnimThread()).start();
	}
	
	public boolean isStart()
	{
		return (start&&!over);
	}
	public boolean isOver()
	{
		return over;
	}
	
	public Icon nextIcon()
	{
		if(index > anim.length -1)
		{
			index = 0;
			repeatTime--;
			if(repeatTime < 0)
			{
				return null;
			}
			
		}
		return anim[index++];
	}
	public void setLastShowIcon(int index)
	{
		this.lastShow = index;
	}
	
	class AnimThread implements Runnable
	{
		private boolean hasDrawed = false;
		private int DEFAULT_FPS = 60;
		private int gameState = 0;
		private long nowFPS;
	
		private boolean xOver,yOver;
		private boolean allOver;
		
		public void run()
		{
			// 计算出指定FPS数值中，每帧需要多少时间  
			long fpsTime = (long) ((Double.valueOf(1000) / Double.valueOf(DEFAULT_FPS)) * 1000000);  
			// 绘制图像前的时间戳  
			long now = 0;  
			// 每次绘制图像耗时（毫秒）  
			long total = 0;  
			while(true) {  
				now = System.nanoTime();  
				// 绘制图像  
//		          case 0://主菜单状态
				frameTime--;
				if(frameTime<0)
				{
					frameTime = frameIniTime;
					Icon next = nextIcon();
					if(next == null)
					{
						start = false;
						over = true;
						setIcon(anim[lastShow]);
						index = lastShow;
						return;
					}else
					{
						setIcon(next);
					}
				}
				
				start = true;
				over = false;
				try{  
					// 除去绘制之后还需要休眠的时间  
					total = System.nanoTime() - now;  
				
					if(total > fpsTime){  
						nowFPS = 1000000*1000/total;
						// 如果本次绘制时间超过每帧需要绘制的时间，则直接继续绘制  
						continue;  
					}  
					Thread.sleep((fpsTime - (System.nanoTime()- now)) / 1000000);  
					total = System.nanoTime() - now;  
					nowFPS = 1000000*1000/total;
				} catch (InterruptedException e) {  
					e.printStackTrace();  
				}  
				while((System.nanoTime()- now) < fpsTime){  
					// 使用循环，精确控制每帧绘制时长  
					System.nanoTime();  
				}  
			}  
		}
	}
	
}
